package com.soujiayi.coupon;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

public class FileUtil {
	// 得到当前外部存储设备的目录
	public static String fileRoot = getSDPath() + "/com.silverpalm/caches";
	private static final String WHOLESALE_CONV = ".cache";

	// sd卡是否存在
	public static boolean ifSdExist() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/**** 取SD卡路径不带/ ****/
	public static String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		// 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();
			// 获取跟目录
		}
		if (sdDir != null) {
			return sdDir.getAbsolutePath();
		} else {
			return "";
		}
	}

	public static String convertToImageName(String url)
	{
		if(url == null)
		{
			return null;
		}
	
		 return  url.substring(url.lastIndexOf('/')+1,url.length());
	}
	
	
	/** 将url转成文件名 **/
	public static String convertUrlToFileName(String url) {
		if (url == null) {
			return null;
		}
		// String[] strs = url.split("/");
		// return strs[strs.length - 1] + WHOLESALE_CONV;
		char r[] = { ':', '/', '\\', '?', '*', '>', '<', '|', '"' };
		for (int i = 0; i < r.length; i++) {
			url = url.replace(r[i], '!');
		}
		return url + WHOLESALE_CONV;
	}

	public static String getRootPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	// 获得文件路径
	public static File[] getFiles(String path) {
		File file = new File(path);
		return file.listFiles();
	}

	// 
	public static void saveFile(String filename, String content, Context context) {
		FileOutputStream fos = null;
		try {
			fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write(content.getBytes());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	// 保存文本
	public static void saveFile(String filename, String content, String path) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(path, filename));
			fos.write(content.getBytes());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

//	// 将bitmap保存到本地
//	public static void saveFile(Bitmap bitmap, String path, String filename) {
//		FileOutputStream fos = null;
//		try {
//			fos = new FileOutputStream(new File(path, filename));
//			fos.write(ImageUtil.BitmapToBytes(bitmap));
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} finally {
//			if (fos != null) {
//				try {
//					fos.close();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
//	}

//	// 将bitmap保存到默认路径
//	public static void saveFile(Bitmap bitmap, String filename, Context mContext) {
//		FileOutputStream fos = null;
//		try {
//			fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
//			fos.write(ImageUtil.BitmapToBytes(bitmap));
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} finally {
//			if (fos != null) {
//				try {
//					fos.close();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
//	}

	public static void saveFile(byte[] data, String filename, Context mContext) {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write(data);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 保存图片为PNG
	 * Insufficient privileges
	 * @param bitmap
	 * @param name
	 */
	public static void savePNG_After(Bitmap bitmap, String path, String name) {
		File file = new File(path, name);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
		if(bitmap!=null)
		{
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
			}
		}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void savePNG_After(Bitmap bitmap, String filename,
			Context mContext) {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
				fos.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 保存图片为JPEG
	 * 
	 * @param bitmap
	 * @param path
	 */
	public static void saveJPGE_After(Bitmap bitmap, String path, String name) {
		File file = new File(path, name);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void saveJPGE_After(Bitmap bitmap, String filename,
			Context mContext) {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)) {
				fos.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static String readFile(String filename, Context context) {
		FileInputStream fis = null;
		ByteArrayOutputStream baos = null;
		try {
			fis = context.openFileInput(filename);
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 4];
			int length = 0;
			while (-1 != (length = fis.read(buffer))) {
				baos.write(buffer, 0, length);
			}
			byte[] data = baos.toByteArray();
			return new String(data);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static String readTxtFile(String txtPath) {
		FileInputStream fis = null;
		ByteArrayOutputStream baos = null;
		try {
			fis = new FileInputStream(new File(txtPath));
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 4];
			int length = 0;
			while (-1 != (length = fis.read(buffer))) {
				baos.write(buffer, 0, length);
			}
			byte[] data = baos.toByteArray();
			return new String(data);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	// 判断是否是图片
	public static boolean ifTypeImage(String path) {
		String typeName = getFileType(path);
		typeName = typeName.toLowerCase();
		if (typeName.equals(".png") || typeName.equals(".jpg")) {
			return true;
		}
		return false;
	}

	// 判断是否是文件
	public static boolean ifTypeTxt(String path) {
		String typeName = getFileType(path);
		typeName = typeName.toLowerCase();
		if (typeName.equals(".txt")) {
			return true;
		}
		return false;
	}

	// 返回文件类型
	public static String getFileType(String path) {
		int len = path.length();
		return path.substring(len - ".jpg".length(), len);
	}

	/**
	 * 在SD卡上创建文件
	 * 
	 * @throws IOException
	 */
	public static File creatFileInSDCard(String fileName, String dir)
			throws IOException {
		File file = new File(getSDPath() + dir + File.separator + fileName);
		file.createNewFile();
		return file;
	}

	/**
	 * 在SD卡上创建目录
	 */
	public static File createSDDir(String dir) {
		File dirFile = new File(getSDPath() + dir + File.separator);
		return dirFile;
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public static boolean isFileExist(String fileName, String path) {
		File file = new File(getSDPath() + path + File.separator + fileName);
		return file.exists();
	}

	/**
	 * 将一个InputStream里面的数据写入SD卡中
	 */
	public static File writeSDFromInput(String path, String fileName,
			InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			createSDDir(path);
			file = creatFileInSDCard(fileName, path);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			int i;
			while (-1 != (i = input.read(buffer))) {
				output.write(buffer, 0, i);
			}
			output.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	public static void writeSDFromInput(String filename, InputStream input,
			Context mContext) {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
			byte buffer[] = new byte[4 * 1024];
			int i;
			while (-1 != (i = input.read(buffer))) {
				fos.write(buffer, 0, i);
			}
			fos.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	// 递归删除指定的目录下的文件
	public static void deleteDir(String path) {
		File file = new File(path);
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (File subFile : files) {
					if (subFile.isDirectory())
						deleteDir(subFile.getPath());
					else
						subFile.delete();
				}
			}
			file.delete();
		}
	}
}
